﻿using ETModel;

namespace ETHotfix {
    public class InnerMessageDispatcher : IMessageDispatcher {
        public void Dispatch(Session session, ushort opcode, object message) {
            // 收到actor消息,放入actor队列
            switch (message) {
                case IActorRequest iActorRequest: {
                        //有指定actor的消息(要求回复的消息,如G2M的登录)
                        Entity entity = (Entity)Game.EventSystem.Get(iActorRequest.ActorId);
                        if (entity == null) {
                            Log.Warning($"not found actor: {message}");
                            ActorResponse response = new ActorResponse {
                                Error = ErrorCode.ERR_NotFoundActor,
                                RpcId = iActorRequest.RpcId
                            };
                            session.Reply(response);
                            return;
                        }

                        MailBoxComponent mailBoxComponent = entity.GetComponent<MailBoxComponent>();
                        if (mailBoxComponent == null) {
                            ActorResponse response = new ActorResponse {
                                Error = ErrorCode.ERR_ActorNoMailBoxComponent,
                                RpcId = iActorRequest.RpcId
                            };
                            session.Reply(response);
                            Log.Error($"actor not add MailBoxComponent: {entity.GetType().Name} {message}");
                            return;
                        }

                        mailBoxComponent.Add(new ActorMessageInfo() { Session = session, Message = iActorRequest });
                        return;
                    }
                case IActorMessage iactorMessage: {
                        //有指定actor的消息(不需要回复的消息,如G2M的移动单位)
                        Entity entity = (Entity)Game.EventSystem.Get(iactorMessage.ActorId);
                        if (entity == null) {
                            Log.Error($"not found actor: {message}");
                            return;
                        }
                        //实体必须挂载邮筒组件
                        MailBoxComponent mailBoxComponent = entity.GetComponent<MailBoxComponent>();
                        if (mailBoxComponent == null) {
                            Log.Error($"actor not add MailBoxComponent: {entity.GetType().Name} {message}");
                            return;
                        }
                        //发给这个邮筒自行处理
                        mailBoxComponent.Add(new ActorMessageInfo() { Session = session, Message = iactorMessage });
                        return;
                    }
                default: {
                        //非指定actor的消息,
                        Game.Scene.GetComponent<MessageDispatcherComponent>().Handle(session, new MessageInfo(opcode, message));
                        break;
                    }
            }
        }
    }
}
